﻿namespace Sitecore.ChangesTracker.UI
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using Sitecore.Shell.Applications.ContentManager.Galleries;
  using Sitecore.Globalization;
  using Sitecore.Data.Items;
  using Sitecore.Web.UI.HtmlControls;
  using Sitecore.Diagnostics;
  using Sitecore.Web.UI.Sheer;
  using Sitecore.Data;
  using Sitecore.Web.UI.XmlControls;
  using Sitecore.Web;
  using Sitecore.Configuration;
  using Sitecore.Data.Managers;
  using Sitecore.Shell;

  public class GalleryLanguagesForm : GalleryForm 
  {
    // Fields
    protected Scrollbox Languages;
    protected GalleryMenu Options;

    // Methods
    private static Item GetCurrentItem()
    {
      string str2 = WebUtil.GetSessionString("itm_id");
      string lang = WebUtil.GetSessionString("arc_lang_db");
      Language language = string.IsNullOrEmpty(lang) ? Context.ContentLanguage : Language.Parse(lang);
      Sitecore.Data.Version version = Sitecore.Data.Version.Parse(WebUtil.GetSessionString("arc_ver_db","0"));
      return Context.ContentDatabase.Items[str2, language, version];
    }

    public override void HandleMessage(Message message)
    {
      Assert.ArgumentNotNull(message, "message");
      if (message.Name != "event:click")
      {
        switch (message.Name)
        {
          case "compare:set_db":
            WebUtil.SetSessionValue("arc_lang_db", message.Arguments["language"]);
            WebUtil.SetSessionValue("arc_ver_db", message.Arguments["version"]);
            break;
          case "compare:set_cp":
            WebUtil.SetSessionValue("arc_lang_cp", message.Arguments["language"]);
            WebUtil.RemoveSessionValue("arc_ver_cp"); 
            break;
          default:
            base.Invoke(message, true);
            break;
        }
        SheerResponse.Eval("scForm.getParentForm().invoke(\"archive:refresh\")");
        SheerResponse.Eval("scForm.getParentForm().Content.closeGallery(scForm.browser.getFrameElement().id)");
      }
    }

    protected override void OnLoad(EventArgs e)
    {
      Assert.ArgumentNotNull(e, "e");
      base.OnLoad(e);
      if (!Context.ClientPage.IsEvent)
      {
        string postfix = WebUtil.GetQueryString("view");
        string command = "compare:set" + postfix;
        if (postfix == "_db")
        {
          Item currentItem = GetCurrentItem();
          if (currentItem != null)
          {
            foreach (Language language in currentItem.Languages)
            {
              ID languageItemId = LanguageManager.GetLanguageItemId(language, currentItem.Database);
              if (!ItemUtil.IsNull(languageItemId))
              {
                Item item2 = currentItem.Database.GetItem(languageItemId);
                if (((item2 == null) || !item2.Access.CanRead()) || (item2.Appearance.Hidden && !UserOptions.View.ShowHiddenItems))
                {
                  continue;
                }
              }
              BuildOption(command , language,postfix);

            }
          }
        }
          if(postfix=="_cp")
          {
            string languages = WebUtil.GetSessionString("languages");
          if(!string.IsNullOrEmpty(languages))
          {
            foreach(string lang in languages.Split(new char[]{'|'}))
            {
              this.BuildOption(command, Language.Parse(lang), postfix);
            }
          }

          Context.ClientPage.AddControl(this.Options, new MenuLine());
          //Item item = Client.CoreDatabase.GetItem("/sitecore/content/Applications/Content Editor/Menues/Languages");
          //if (item != null)
          //{
          //  this.Options.AddFromDataSource(item, string.Empty);
          //}
          //Context.ClientPage.AddControl(this.Options, new MenuLine());
        }
      }
    }

    //private void BuildOption(Item currentItem, Language language)
    //{
    //  XmlControl control = ControlFactory.GetControl("Gallery.Languages.Option") as XmlControl;
    //  Assert.IsNotNull(control, typeof(XmlControl));
    //  Context.ClientPage.AddControl(this.Languages, control);
    //  Item item3 = currentItem.Database.GetItem(currentItem.ID, language);
    //  if (item3 != null)
    //  {
    //    int length = item3.Versions.GetVersionNumbers(false).Length;
    //    string str = (length == 1) ? Translate.Text("1 version.") : Translate.Text("{0} versions.", new object[] { length.ToString() });
    //    control["Icon"] = LanguageService.GetIcon(language, currentItem.Database);
    //    System.Globalization.CultureInfo cultureInfo = language.CultureInfo;
    //    control["Header"] = Language.GetDisplayName(cultureInfo);
    //    control["Description"] = str;
    //    control["Click"] = string.Format("compare:set_db(id={0},language={1},version=0)", currentItem.ID, language);
    //    if (language.Name.Equals(WebUtil.GetSessionString("arc_lang_db", Context.ContentLanguage.Name), StringComparison.OrdinalIgnoreCase))
    //    {
    //      control["ClassName"] = "scMenuPanelItemSelected";
    //    }
    //    else
    //    {
    //      control["ClassName"] = "scMenuPanelItem";
    //    }
    //  }
    //}
    private void BuildOption(string command,Language language,string postfix)
    {
      XmlControl control = ControlFactory.GetControl("Gallery.Languages.Option") as XmlControl;
      Assert.IsNotNull(control, typeof(XmlControl));
      Context.ClientPage.AddControl(this.Languages, control);
      //Item item3 = currentItem.Database.GetItem(currentItem.ID, language);
      //if (item3 != null)
      //{
        //int length = item3.Versions.GetVersionNumbers(false).Length;
        //string str = (length == 1) ? Translate.Text("1 version.") : Translate.Text("{0} versions.", new object[] { length.ToString() });
        control["Icon"] = LanguageService.GetIcon(language, Context.ContentDatabase);
        System.Globalization.CultureInfo cultureInfo = language.CultureInfo;
        control["Header"] = Language.GetDisplayName(cultureInfo);
        //control["Description"] = str;
        control["Click"] = string.Format(command+"(language={0},version=0)", language);
        if (language.Name.Equals(WebUtil.GetSessionString("arc_lang"+postfix, Context.ContentLanguage.Name), StringComparison.OrdinalIgnoreCase))
        {
          control["ClassName"] = "scMenuPanelItemSelected";
        }
        else
        {
          control["ClassName"] = "scMenuPanelItem";
        }
      //}
    }
  }
}
